package com.sino.operation.service.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sino.operation.commons.ConstantValue;
import com.sino.operation.commons.commonEnum.AspectFlag;
import com.sino.operation.commons.commonEnum.StatusInfoEnum;
import com.sino.operation.commons.commonEnum.VoucherType;
import com.sino.operation.dto.Dto;
import com.sino.operation.entity.*;
import com.sino.operation.param.out.CashDepositParam;
import com.sino.operation.param.inner.TaskBackPublicParam;
import com.sino.operation.param.inner.TaskCompletePublicParam;
import com.sino.operation.param.out.EscReciveByCounter;
import com.sino.operation.peripheral.esc.request.CoreHead;
import com.sino.operation.peripheral.esc.request.EscBody;
import com.sino.operation.peripheral.esc.request.NetHandle;
import com.sino.operation.peripheral.esc.request.core.EscCore2114Param;
import com.sino.operation.peripheral.esc.request.core.body.EscBodyCore2114;
import com.sino.operation.util.EscRequestTestUtil;
import com.sino.operation.util.PersistenceUtil;
import com.sino.operation.util.StringUtil;
import com.sino.operation.util.TimeUtil;
import com.sino.operation.vo.PublicInfo;
import com.sino.operation.vo.current.TaskOtherCompleteParam;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Title: Exec_710305
 * @Description: 对公保证金
 * @Author dengls
 * @date 2021/10/19 16:40
 */
@Slf4j
public class Exec_710305 extends BaseAction {

    public Exec_710305(Map varMap, BizTranslist bizTranslist, SysAbMessage sysAbMessage, BizOperateLog bizOperateLog, Object registerTable, Object receiveParam) {
        super(varMap, bizTranslist, sysAbMessage, bizOperateLog, registerTable, receiveParam);
    }

    public Exec_710305(String journalNo, SysAbMessage sysAbMessage) {
        super(journalNo, sysAbMessage);
    }

    @Override
    public PersistenceUtil executeReception() throws Exception {
        log.info("对公保证金发起开始");
        EscReciveByCounter receiveParam = (EscReciveByCounter) this.receiveParam;
        EscBody escBody = receiveParam.getEscBody();
        PublicInfo publicInfo = escBody.getPublicInfo();
        String json = JSONObject.toJSONString(receiveParam.getEscBody().getObject());
        CashDepositParam cashDepositParam = JSONObject.parseObject(json, CashDepositParam.class);
        log.info("流程发起报文:" + cashDepositParam.toString());

        String tellerPost = publicInfo.getTellerPost();//岗位号
        String tellerCode = publicInfo.getTellerCode();//柜员号
        String tellerName = publicInfo.getTellerName();//柜员
        String tranDate = publicInfo.getTranDate();//发起日期
        String tranTime = publicInfo.getTranTimeStamp();//发起时间
        String orgCode = publicInfo.getOrgCode();//机构号
        String orgName = publicInfo.getOrgName();//机构名
        String imageId = publicInfo.getImageId();//影像套号
        String tranCode = publicInfo.getTranCode();//交易码
        String businessType = publicInfo.getBusinessType();//业务类型

        String product_type = cashDepositParam.getProduct_type();//产品类型
        String source = cashDepositParam.getSource();//资金来源
        String zcpzle = cashDepositParam.getZcpzle();//转出凭证类型
        String wgzhxz = cashDepositParam.getWgzhxz();//外管账户性质
        String business_no = cashDepositParam.getBusiness_no();//业务编号
        String printornot = cashDepositParam.getPrintornot();//是否打印证实书
        String batch_no = cashDepositParam.getBatch_no();//凭证批次号
        String batch_number = cashDepositParam.getBatch_number();//凭证号码
        String credentials_type = cashDepositParam.getCredentials_type();//证件类型（经办人）
        String credentials_no = cashDepositParam.getCredentials_no();//证件号码（经办人）
        String client_name = cashDepositParam.getClient_name();//客户名称（经办人）
        String credentials_starttime = cashDepositParam.getCredentials_starttime();//证件起始日期（经办人）
        String credentials_endtime = cashDepositParam.getCredentials_endtime();//证件截止日期（经办人）
        String phone = cashDepositParam.getPhone();//电话号码（经办人）
        String nationality = cashDepositParam.getNationality();//国籍（经办人）
        String tjygh = cashDepositParam.getTjygh();//推荐员工号
        String tjrxm = cashDepositParam.getTjrxm();//推荐人姓名
        String bz = cashDepositParam.getBz();//币种
        String account_type = cashDepositParam.getAccount_type();//账户性质
        String fxfs = cashDepositParam.getFxfs();//付息方式
        String journalNo = this.bizTranslist.getJournalNo();

        if (zcpzle == null || "".equals(zcpzle)) {
            log.error("未获取到凭证种类，流水号：" + journalNo);
            return null;
        }
        String cps_flag = null;
        // 确定切片标志 放入流程变量 加入报文 更新登记簿表
        if (VoucherType.VOUCHERTYPE01.getValue().equals(zcpzle) || VoucherType.VOUCHERTYPE38.getValue().equals(zcpzle)
                || VoucherType.VOUCHERTYPE71.getValue().equals(zcpzle) || VoucherType.VOUCHERTYPE73.getValue().equals(zcpzle)) {
            cps_flag = AspectFlag.AspectFlag1.getValue();//切片
        } else {
            cps_flag = AspectFlag.AspectFlag2.getValue();//整单
        }

        cashDepositParam.setJournalNo(journalNo);
        escBody.setObject(cashDepositParam);
        receiveParam.setEscBody(escBody);
        BizMarginOpenAccount marginOpenAccount = new BizMarginOpenAccount();
        marginOpenAccount.setJournalNo(journalNo);
        marginOpenAccount.setProductType(product_type);
        marginOpenAccount.setSource(source);
        marginOpenAccount.setCerty(zcpzle);
        marginOpenAccount.setWgzhxz(wgzhxz);
        marginOpenAccount.setBusinessNo(business_no);
        marginOpenAccount.setPrintOrNot(printornot);
        marginOpenAccount.setCerno(batch_no);
        marginOpenAccount.setCerno2(batch_number);
        marginOpenAccount.setCredentialsType(credentials_type);
        marginOpenAccount.setCredentialsNo(credentials_no);
        marginOpenAccount.setClientName(client_name);
        marginOpenAccount.setCredentialsStarTime(credentials_starttime);
        marginOpenAccount.setCredentialsEndTime(credentials_endtime);
        marginOpenAccount.setPhone(phone);
        marginOpenAccount.setNationality(nationality);
        marginOpenAccount.setTjrxm(tjrxm);
        marginOpenAccount.setTjygh(tjygh);
        marginOpenAccount.setBz(bz);
        marginOpenAccount.setCpsFlag(cps_flag);
        marginOpenAccount.setImageId(imageId);
        marginOpenAccount.setTransCode(tranCode);
        marginOpenAccount.setBsty(businessType);
        if (ConstantValue.DWDQBZJ.equals(product_type)) {
            //定期保证金单独字段
            marginOpenAccount.setAccty(account_type);
            marginOpenAccount.setFxfs(fxfs);
        }
        this.bizTranslist.setSliceFlage(cps_flag);
        varMap.put("cps_flag", cps_flag);
        persistence.addEntity(marginOpenAccount);
        return persistence;
    }

    //整单1提交方法
    public PersistenceUtil executeTotalEntry1() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageTotal1(json);
        return persistence;
    }

    //整单2提交方法
    public PersistenceUtil executeTotalEntry2() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageTotal2(json);
        return persistence;
    }

    //修正岗提交方法
    public PersistenceUtil executeFixed() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        String sliceFlage = bizTranslist.getSliceFlage();
        String journalNo = bizTranslist.getJournalNo();
        BizMarginOpenAccount bizMarginOpenAccount = bizMarginOpenAccountMapper.selectById(journalNo);
        Map<String, Map> infoInputs = receiveParam.getInfoInputs();
        bizMarginOpenAccount = Exec_710305_Util.CollectionHandle(infoInputs, bizMarginOpenAccount);//归集登记薄数据
        if (StatusInfoEnum.SLICE_FLAGE.getCode().equals(sliceFlage)) {
            this.varMap.put("cps_flag", StatusInfoEnum.SLICE_FLAGE.getCode());
        } else {
            this.varMap.put("cps_flag", StatusInfoEnum.TOTAL_FLAGE.getCode());
        }
        this.sysAbMessage.setMessageAuditing(json);
        this.sysAbMessage.setMessage(json);
        persistence.addEntity(bizMarginOpenAccount);
        return persistence;
    }

    //复核岗提交方法
    public PersistenceUtil executeReview() {
        return persistence;
    }

    //授权岗提交方法
    @Override
    public PersistenceUtil executeAuth() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        TaskCompletePublicParam taskCompletePublicParam = receiveParam.getTaskCompletePublicParam();
        String completeMark = receiveParam.getTaskCompletePublicParam().getCompleteMark();
        String json = JSON.toJSONString(receiveParam);
        this.bizTranslist.setBackFlag(completeMark);//保存提交标志
        if (ConstantValue.CONDITION_PASS.equals(completeMark)) {
            BizAddImage bizAddImage = new BizAddImage();
            bizAddImage.setId(StringUtil.getId());
            bizAddImage.setJournalNo(taskCompletePublicParam.getJournalNo());
            bizAddImage.setStartTeller(taskCompletePublicParam.getCenterTellerNo());
            bizAddImage.setStartTellerName(taskCompletePublicParam.getCenterTellerName());
            bizAddImage.setStartDate(TimeUtil.getStandardTime());
            bizAddImage.setState("0");//默认未补扫
            bizAddImage.setNoPassReason(taskCompletePublicParam.getReason());
            persistence.addEntity(bizAddImage);
        }
        this.sysAbMessage.setMessageAuth(json);
        this.varMap.put("auth_flag", "0");

        return persistence;
    }

    @Override
    public PersistenceUtil executeNetwork() throws Exception {
        System.out.println("进入了网点");
        varMap.put("externel", "0");
        return this.persistence;
    }

    //回退方法
    @Override
    public PersistenceUtil executeBack() throws Exception {
        TaskBackPublicParam receiveParam = (TaskBackPublicParam) this.receiveParam;
        String backMark = receiveParam.getBackMark();
        String json = JSON.toJSONString(receiveParam);
        this.bizTranslist.setBackFlag(backMark);//保存提交标志
        this.sysAbMessage.setMessageAuth(json);
        this.varMap.put("auth_flag", backMark);
        return persistence;
    }

    @Override
    public Dto executeGetTaskList(NetHandle netHandle) {
        return new Dto();
    }

    @Override
    public PersistenceUtil executeTerminal() throws Exception {
        return persistence;
    }

    //整单获取
    @Override
    public Object executeTotalEntryTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //修正岗获取
    public Object executeFixedTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //复核岗获取
    public Object executeReviewTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //授权岗获取
    @Override
    public Object executeAuthTask() throws Exception {
        BizMarginOpenAccount bizMarginOpenAccount = bizMarginOpenAccountMapper.selectById(journalNo);
        Map<String, Map> otherFields = new HashMap<>();
        Map<String, Map> focusFields = new HashMap<>();
        Map<String, Map> authResult = new HashMap<>();
        QueryWrapper<BizDictSet> wrapper = new QueryWrapper<>();
        wrapper.eq("FIELD_TRANS_CODE", bizMarginOpenAccount.getTransCode());
        wrapper.eq("FIELD_TRANS_TYPE", bizMarginOpenAccount.getBsty());
        List<BizDictSet> dictSets = bizDictSetMapper.selectList(wrapper);//查询交易字段
        String messageTotal1 = sysAbMessage.getMessageTotal1();
        Map<String, Map> infoInputs = JSON.parseObject(messageTotal1, TaskOtherCompleteParam.class).getInfoInputs();
        Set<String> set = infoInputs.keySet();//中心录入字段
        String s = JSON.toJSONString(bizMarginOpenAccount);
        Map map = JSON.parseObject(s, Map.class);
        for (BizDictSet dictSet : dictSets) {
            String fieldEg = dictSet.getFieldEg();
            String field = StringUtil.slashToFirstLetterUpper(fieldEg);//转小写
            if ("1".equals(dictSet.getFieldFocus())) {
                HashMap<String, Object> focusField = new HashMap<>();
                if (set.contains(fieldEg)) {
                    focusField.put("sourceFlag", ConstantValue.SOURCE_FlAG_CENTER);//中心录入
                } else {
                    focusField.put("sourceFlag", ConstantValue.SOURCE_FlAG_BRANCH);//网点录入
                }
                focusField.put("CHE", dictSet.getFieldCn());//中文名
                focusField.put("value", map.get(field));//值
                focusFields.put(fieldEg, focusField);
            } else {
                HashMap<String, Object> otherField = new HashMap<>();
                if (set.contains(fieldEg)) {
                    otherField.put("sourceFlag", ConstantValue.SOURCE_FlAG_CENTER);//中心录入
                } else {
                    otherField.put("sourceFlag", ConstantValue.SOURCE_FlAG_BRANCH);//网点录入
                }
                otherField.put("CHE", dictSet.getFieldCn());
                otherField.put("value", map.get(field));
                otherFields.put(fieldEg, otherField);
            }
        }
        authResult.put("otherFields", otherFields);
        authResult.put("focusFields", focusFields);
        return authResult;
    }

    @Override
    public PersistenceUtil executeCharge() throws Exception {
        BizMarginOpenAccount bizMarginOpenAccount = bizMarginOpenAccountMapper.selectById(journalNo);
        CoreHead coreHead = new CoreHead();
        coreHead.setReqResFlg("req");
        String core2114Url = urlUtil.getCoreUrl("2114");
        String escToken = this.redis.opsForValue().get("escToken");
        //产品编号、货币代号、账户分类、账户属性、计息标志、资金来源、客户号、预付息标志
//        EscCore2114Param escCore2114Param = EscRequestTestUtil.getEscCore2114Param(journalNo, "2114", escToken);
        EscBodyCore2114 escBodyCore2114 = EscBodyCore2114.builder().coreHead(coreHead).prodCode(bizMarginOpenAccount.getProductType())
//                .ccyCodeNum(bizMarginOpenAccount.getBz()).acctClasf(bizMarginOpenAccount.getFxfs()).acctAttr().intCalnFlg()
//                .cptlSrc(bizMarginOpenAccount.getSource()).custNum().advIntPymtFlg()
                .build();
//        escCore2114Param.setEscBodyCore2114(escBodyCore2114);
        //发往核心记账及相应机制
        return null;
    }
}
